<template lang="pug">
  Button(type='ghost', @click='onClick', :disabled='disabled') {{ label }}
</template>

<script>
export default {
  props: {
    readyLabel: {
      type: String,
      default: '开始倒数'
    },
    countingLabel: {
      type: String,
      default: '%count'
    },
    countDown: {
      type: Number,
      required: true
    },
    beforeClick: {
      type: Function
    }
  },
  data () {
    return {
      clicked: false,
      disabled: false,
      timeout: this.countDown
    }
  },
  computed: {
    label () {
      return this.timeout === this.countDown
        ? this.readyLabel
        : this.countingLabel.replace('%count', this.timeout)
    }
  },
  beforeDestroy () {
    clearTimeout(this.timer)
    this.timer = null
  },
  methods: {
    async onClick () {
      let next = true
      if (this.beforeClick) {
        let ret = await this.beforeClick()
        next = ret !== false
      }
      if (next) {
        console.log('next')
        this.counting()
        this.clicked = true
        this.disabled = true
        this.$emit('click')
      }
    },
    counting () {
      clearTimeout(this.timer)

      this.timeout--
      if (this.timeout > 0) {
        this.timer = setTimeout(this.counting, 1000)
      } else {
        this.timeout = this.countDown
        this.disabled = false
        this.$emit('count-down-end')
      }
    }
    // getLabel () {
    //   if (this.timeout === 0) {
    //     this.timeout = this.countDown
    //   }
    //   return this.countingLabel.replace('%count', this.timeout)
    // }
  }
}
</script>
